package com.dlc.apk.ui.view

import android.animation.Animator
import android.media.MediaPlayer.*
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.VideoView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.dlc.apk.ui.view.AdPlayer.AdDataItem.AdType
import com.dlc.apk.utils.LogPlus
import java.text.SimpleDateFormat
import java.util.*

class AdPlayer(private val adImageView: ImageView, private val adVideoView: VideoView) {
    private var adDataItemList: List<AdDataItem>? = null
    private var currentPlayIndex = 0
    private var isStopped = false
    private var handler: Handler? = null

    var onAdPlayListener: OnAdPlayListener? = null

    init {
        handler = Handler(Looper.getMainLooper())
    }

    /**
     * 设置数据源
     */
    fun setDataSource(adDataItemList: List<AdDataItem>?) {
        this.adDataItemList = adDataItemList
        currentPlayIndex = 0
    }

    /**
     * 播放
     */
    fun play() {
        if (isStopped) {
            showDefaultAd()
            return
        }
        if (adDataItemList == null || adDataItemList!!.isEmpty()) {
            return
        }
        if (adDataItemList!![currentPlayIndex].adType == AdType.IMAGE) {
            displayImage()
        } else {
            displayVideo()
        }
    }

    fun showDefaultAd() {
        adImageView.alpha = 1f
        adVideoView.alpha = 0f
        adImageView.visibility = View.VISIBLE
        adVideoView.visibility = View.GONE
        adVideoView.pause()
        //显示图片
        Glide.with(adImageView.context)
            .load(defaultAdUrl)
            .transform(CenterCrop(), RoundedCorners(1))
//            .error(R.mipmap.ic_fh)
//            .placeholder(R.mipmap.ic_launcher)
            .into(adImageView)
    }

    /**
     * 重启播放
     */
    fun restart() {
        currentPlayIndex = 0
        isStopped = false
        play()
    }

    /**
     * 停止播放
     */
    fun stop() {
        isStopped = true
        adVideoView.visibility = View.GONE
        adImageView.visibility = View.GONE
        //showDefaultAd()
        if (lastPlayedAdDataItem != null && lastPlayedAdDataItem!!.adType == AdType.VIDEO) {
            adVideoView.pause()
        }
    }

    /**
     * 恢复播放
     */
    fun resume() {
        isStopped = false
        play()
        if (lastPlayedAdDataItem != null && lastPlayedAdDataItem!!.adType == AdType.VIDEO) {
            adVideoView.resume()
        }
    }

    private fun next() {
        if (this.adDataItemList!!.isEmpty()) {
            return
        }
        currentPlayIndex = (currentPlayIndex + 1) % this.adDataItemList!!.size
        play()
    }

    private var lastPlayedAdDataItem: AdDataItem? = null

    /**
     * 显示图片
     */
    private fun displayImage() {
        val currentAdDataItem = this.adDataItemList?.get(currentPlayIndex)
        if (currentAdDataItem == null) {
            next()
            return
        }
        //非此时段则不显示
        if (!isInDate(currentAdDataItem.startTimestamp, currentAdDataItem.endTimestamp)) {
            adImageView.visibility = View.GONE
            //播放下一个
            next()
            return
        }
        //非此时段则不显示
        if (!isInNow(currentAdDataItem.startTime, currentAdDataItem.endTime)) {
            adImageView.visibility = View.GONE
            //播放下一个
            next()
            return
        }
        adImageView.visibility = View.VISIBLE
        if (lastPlayedAdDataItem == null || currentAdDataItem != lastPlayedAdDataItem) {
            //淡入
            adImageView.alpha = 0f
            adImageView.animate().alpha(1f).setDuration(1000).setListener(null)
            //淡出
            adVideoView.visibility = View.VISIBLE
            adVideoView.animate().alpha(0f).setDuration(1000).setListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(p0: Animator?) {
                }

                override fun onAnimationEnd(p0: Animator?) {
                    adVideoView.visibility = View.GONE
                }

                override fun onAnimationCancel(p0: Animator?) {

                }

                override fun onAnimationStart(p0: Animator?) {
                }
            })
        }
        lastPlayedAdDataItem = currentAdDataItem
        //显示图片
        Glide.with(adImageView.context)
            .load(currentAdDataItem.url)
            //.transform(CenterCrop(), RoundedCorners(1))
//            .error(R.mipmap.ic_fh)
//            .placeholder(R.mipmap.ic_launcher)
            .fitCenter()
            .into(adImageView)

        //延时切换
        handler?.removeCallbacks(delayRunnable)
        handler?.postDelayed(delayRunnable, currentAdDataItem.duration * 1000L)
        //该广告播放一次
        onAdPlayListener?.onPlayed(currentAdDataItem)
    }

    val delayRunnable = Runnable {
        next()
    }

    /**
     * 显示视频
     */
    private fun displayVideo() {
        val currentAdDataItem = this.adDataItemList?.get(currentPlayIndex)
        if (currentAdDataItem == null) {
            next()
            return
        }
        //非此时段则不显示
        if (!isInDate(currentAdDataItem.startTimestamp, currentAdDataItem.endTimestamp)) {
            LogPlus.e("###非当前日期时间段,不播放此广告,id->${currentAdDataItem}")
            adVideoView.visibility = View.GONE
            //播放下一个
            next()
            return
        }
        //非此时段则不显示
        if (!isInNow(currentAdDataItem.startTime, currentAdDataItem.endTime)) {
            adVideoView.visibility = View.GONE
            //播放下一个
            next()
            return
        }
        adVideoView.visibility = View.VISIBLE
        if (lastPlayedAdDataItem == null || currentAdDataItem != lastPlayedAdDataItem) {
            //淡入
            adVideoView.alpha = 0f
            adVideoView.animate().alpha(1f).setDuration(1000).setListener(null)
            //淡出
            adImageView.animate().alpha(0f).setDuration(1000).setListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(p0: Animator?) {
                }

                override fun onAnimationEnd(p0: Animator?) {
                    adImageView.visibility = View.GONE
                }

                override fun onAnimationCancel(p0: Animator?) {

                }

                override fun onAnimationStart(p0: Animator?) {
                }
            })
        }
        lastPlayedAdDataItem = currentAdDataItem
        adVideoView.requestFocus()
        if (!adVideoView.isPlaying) {
            //设置视频源
            adVideoView.setVideoURI(Uri.parse(currentAdDataItem.url))
            adVideoView.setOnPreparedListener { mp ->
                //准备好开始播放
                mp.setVolume(0f, 0f)
                mp.start()
            }
            adVideoView.setOnErrorListener { mediaPlayer, i, i2 -> true }
            adVideoView.setOnInfoListener { mediaPlayer, what, extra ->
                LogPlus.e("###onInfo -> $what")
                when (what) {
                    MEDIA_INFO_UNKNOWN -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_UNKNOWN")
                    }
                    MEDIA_INFO_VIDEO_TRACK_LAGGING -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_VIDEO_TRACK_LAGGING")
                    }
                    MEDIA_INFO_VIDEO_RENDERING_START -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_VIDEO_RENDERING_START")
                    }
                    703 -> {
                        LogPlus.e("###媒体信息 网络带宽（703）")
                    }
                    MEDIA_INFO_BUFFERING_START -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_BUFFERING_START")
                    }
                    MEDIA_INFO_BUFFERING_END -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_BUFFERING_END")
                    }
                    MEDIA_INFO_BAD_INTERLEAVING -> {
                        LogPlus.e("###媒体信息 BAD_INTERLEAVING")
                    }
                    MEDIA_INFO_NOT_SEEKABLE -> {
                        LogPlus.e("###媒体信息 NOT_SEEKABLE")
                    }
                    MEDIA_INFO_UNSUPPORTED_SUBTITLE -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_UNSUPPORTED_SUBTITLE")
                        next()
                    }
                    MEDIA_INFO_SUBTITLE_TIMED_OUT -> {
                        LogPlus.e("###媒体信息 MEDIA_INFO_SUBTITLE_TIMED_OUT")
                        next()
                    }
                }

                false//如果方法处理了信息，则为true；如果没有，则为false。返回false或根本没有OnInfoListener，将导致丢弃该信息。
            }
        }

        //切换下一个播放
        adVideoView.setOnCompletionListener {
            LogPlus.e("###视频播放完,继续下一个...")
            next()
        }

        //该广告播放一次
        onAdPlayListener?.onPlayed(currentAdDataItem)
    }

    class AdDataItem(var adType: AdType, var url: String, var duration: Int) {
        //2020.12.13 后台广告数据需要设置在某个时段才显示
        var startTime: String = "00:00:00"
        var endTime: String = "23:59:59"

        var startTimestamp: Long = 0//开始时间戳 毫秒
        var endTimestamp: Long = 0//结束时间戳 毫秒
        //2020.12.13 后台广告数据需要设置在某个时段才显示

        var adId: String? = ""//后台接口需要的广告ID

        var playTimes: Int = 0//播放次数

        enum class AdType {
            IMAGE, VIDEO
        }
    }

    companion object {
        fun isInNow(startTime: String, endTime: String): Boolean {
            val sdf = SimpleDateFormat("HH:mm:ss")
            val startDate = sdf.parse(startTime)
            val endDate = sdf.parse(endTime)
            val nowDate = sdf.parse(sdf.format(Date()))
            return nowDate in startDate..endDate
        }

        fun isInDate(startTimestamp: Long, endTimestamp: Long): Boolean {
            return System.currentTimeMillis() in startTimestamp..endTimestamp
        }

        const val defaultAdUrl = ""

        interface OnAdPlayListener {
            fun onPlayed(adDataItem: AdDataItem)
        }
    }
}